/**
 *    Copyright (c) [2022] [中和农信]
 *    rabbit-mq-plus is licensed under Mulan PSL v2.
 *    You can use this software according to the terms and conditions of the Mulan PSL v2.
 *    You may obtain a copy of Mulan PSL v2 at:
 *             http://license.coscl.org.cn/MulanPSL2
 *    THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *    See the Mulan PSL v2 for more details.
 *
 */
package com.cfpamf.athean.rabbit.mq.plus.consumer.core.schedule;

import javax.annotation.Resource;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import com.cfpamf.athean.rabbit.mq.plus.config.RabbitMqPlusConfig;
import com.cfpamf.athean.rabbit.mq.plus.service.RabbitMqPlusConsumerTaskService;
import com.cfpamf.athena.utils.DateUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 类RabbitMqPlusConsumerInvalidDataProcessorJob.java的实现描述：
 *
 * @author Andy（陈洪桥）2022年11月28 02:12
 */
@Slf4j
@Component
public class RabbitMqPlusConsumerInvalidDataProcessorJob implements ApplicationRunner {

    @Resource
    private RabbitMqPlusConfig rabbitMqPlusConfig;

    @Resource
    private ThreadPoolTaskScheduler rabbitMqPlusSchedulerThreadPool;

    @Resource
    private RabbitMqPlusConsumerTaskService rabbitMqPlusConsumerTaskService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        int deleteInvalidDataByDay = rabbitMqPlusConfig.getDeleteInvalidDataByDay();
        rabbitMqPlusSchedulerThreadPool.scheduleWithFixedDelay(() -> {
            log.info("[rabbitMqPlus]删除消费者任务表中无效数据Job，执行时间：{}", DateUtils.format(DateUtils.nowTime()));
            boolean status = rabbitMqPlusConsumerTaskService.deleteInvalidDataByDay(deleteInvalidDataByDay);
            log.info("[rabbitMqPlus]删除消费者任务表中无效数据调度结果，执行结果：{}", status);
            // 执行时间，当前时间+1天的0点，到之后的每24小时+100内随机分钟数执行（+100内随机分钟数，是为了从概率上避免定时任务多节点，同一时间执行）
        }, DateUtils.getToDayBeginTime(DateUtils.addDay(1)),
            (1000 * 60 * 60 * 24) + (1000 * 60 +((int)(Math.random() * 9000 + 1000))));// new CronTrigger("0 0 10 * * ?")
                                                                        // 间隔时间单位毫秒，//随机生成一个四位整数(int)
                                                                        // (Math.random()*9000+1000)
        log.info("[rabbitMqPlus]删除消费者任务表中无效数据Job启动");
    }

}
